<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshLoding"
      success-text="刷新成功"
      @refresh="getNextPageArticle"
    >
      <van-list
        @load="getNextPageArticle"
        :immediate-check="false"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="item in articles"
          :article-info="item"
          :key="item.art_id"
        >
        </article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticlesAPI } from '@/api'
import ArticleItem from './ArticleItem.vue'
export default {
  name: 'ArticleList',

  components: {
    ArticleItem
  },
  props: {
    channelId: [Number, String]
  },
  data() {
    return {
      articles: [],
      loading: false,
      refreshLoding: false,
      preTimestamp: '',
      finished: false,
      error: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getFIrstPageArticle()
  },
  methods: {
    // 获取第一页的文章数据
    async getFIrstPageArticle() {
      try {
        const { data } = await getArticlesAPI(this.channelId, +new Date())
        //  console.log(data);
        this.articles = data.data.results
        this.preTimestamp = data.data.pre_timestamp
      } catch (error) {
        if (error.response?.status === 400) {
          this.$toast.fail(error.response.data.message)
        } else {
          throw error
        }
      }
    },
    //  获取下一页数据
    async getNextPageArticle() {
      try {
        // 演示随机错误
        // if(Math.random() >0.5){
        //   throw new Error()
        // }
        // 1.发送请求
        const { data } = await getArticlesAPI(this.channelId, this.preTimestamp)
        //  console.log(data);
        // 2.添加数据
        const results = data.data.results
        // 如果是下拉刷新，将数据放在最后 ，否则取反
        if (this.loading) {
          this.articles = [...this.articles, ...results]
        } else {
          this.articles = [...results, ...this.articles]
        }

        // 3.更新时间戳
        this.preTimestamp = data.data.pre_timestamp
        // 4.判断是否加载完毕
        if (data.data.pre_timestamp === null) {
          this.finished = true
        }
      } catch (error) {
        this.error = true
      } finally {
        // 5.手动将loading改为false
        this.loading = false
        this.refreshLoding = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  // 1.定高 2. overflow:auto/scroll/overlay
  height: calc(100vh - 100px - 92px - 83px);
  overflow: auto;
  // css 伪元素  设置滚动条的颜色和宽度
  &::-webkit-scrollbar {
    width: 10px;
    background-color: #fff;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #4ea4fa;
  }
}
</style>
